package com.shujia.hbase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;

import java.io.IOException;

public class Demo4HdfsToHbase {
    /**
     * 读取hdfs数据的mapper
     */
    public static class HdfsToHbaseMapper extends Mapper<LongWritable, Text, Text, NullWritable> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            context.write(value, NullWritable.get());
        }
    }


    public static class HdfsToHbaseRedue extends TableReducer<Text, NullWritable, NullWritable> {

        @Override
        protected void reduce(Text key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {

            String line = key.toString();

            String[] split = line.split(",");

            String id = split[0];
            String name = split[1];
            String age = split[2];
            String igender = split[3];
            String clazz = split[4];

            //创建put

            Put put = new Put(id.getBytes());

            //增加列
            put.add("info".getBytes(), "name".getBytes(), name.getBytes());
            put.add("info".getBytes(), "age".getBytes(), age.getBytes());
            put.add("info".getBytes(), "igender".getBytes(), igender.getBytes());
            put.add("info".getBytes(), "clazz".getBytes(), clazz.getBytes());


            //将数据保存到hbase
            context.write(NullWritable.get(), put);

        }
    }

    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration();

        //指定zk的地址
        configuration.set("hbase.zookeeper.quorum", "master:2181,node1:2181,node2:2181");

        Job job = Job.getInstance(configuration);

        job.setJobName("Demo4HdfsToHbase");

        //设置main所在的类
        job.setJarByClass(Demo4HdfsToHbase.class);


        //设置mapper
        job.setMapperClass(HdfsToHbaseMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(NullWritable.class);

        //设置读数据的路径
        FileInputFormat.setInputPaths(job, new Path("/data/students"));


        //设置reduce

        //创建表     create 'stu2','info'
        TableMapReduceUtil.initTableReducerJob(
                "stu2",
                HdfsToHbaseRedue.class,
                job);


        job.waitForCompletion(true);


    }


}
